package cn.edu.hhu.teacher.dao;

import cn.edu.hhu.teacher.bean.Course;
import cn.edu.hhu.teacher.bean.Teacher;
import cn.edu.hhu.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class CourseDao {
    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    public int addCourse(String cname, String tid) {
        String sql = "insert into course_info (cname, tid) values (?, ?)";
        try {
            return template.update(sql, cname, tid);
        } catch (DataAccessException e) {
            return 0;
        }
    }

    public List<Course> queryCoursesByTid(String tid) {
        String sql = "select * from course_info where tid = ?";
        try {
            return template.query(sql, new BeanPropertyRowMapper<>(Course.class), tid);
        } catch (DataAccessException e) {
            return null;
        }
    }

    public Course queryCourseByTidAndCid(String tid, long cid) {
        String sql = "select * from course_info where cid = ? and tid = ?";
        try {
            return template.queryForObject(sql, new BeanPropertyRowMapper<>(Course.class), cid, tid);
        } catch (DataAccessException e) {
            return null;
        }
    }

    public int deleteCourseByCid(long cid) {
        String sql = "delete from course_info where cid = ?";
        try {
            return template.update(sql, cid);
        } catch (DataAccessException e) {
            return 0;
        }
    }
}